var CONSTS = require('../util/consts');
var moment = require('moment');
var async = require('async');
var Common = require('../util/common');
var CONFIG = require('../config/config').Config;
// var nodemailer = require('nodemailer');
var thenjs = require('thenjs');
var crypto = require("crypto");
var validator = require('validator');
var models = require('../models');
var fs = require('fs-extra');

exports.create = function(req, res, next) {

    var u = req.u;
    var body = req.body;
    var title = Common.cleanString(body.title);
    var html = Common.cleanString(body.html);
    var markdown = Common.cleanString(body.markdown);
    var tags = JSON.parse(body.tags);

    if (Common.isTrimmedEmpty(title)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "title is empty"
        });
        return;
    }

    if (Common.isTrimmedEmpty(html)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "html is empty"
        });
        return;
    }

    if (Common.isTrimmedEmpty(markdown)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "markdown is empty"
        });
        return;
    }

    if (!(tags instanceof Array)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "tags should be array"
        });
        return;
    }

    var article = new models.Article({
        author: u._id,
        title: title,
        html: html,
        markdown: markdown,
        tags: tags,
        last_mod: moment().utc().format(),
        created: moment().utc().format()
    });

    article.save(function(err, article) {
        if (err) {
            res.json(CONSTS.HTTPOK, {
                status: 1,
                error: "db error"
            });
            return;
        }

        res.json(CONSTS.HTTPOK, {
            status: 0,
            msg: article
        });
        ///////////////更新作者文章数量
        ///////////////tags信息维护
        for (var i = 0; i < tags.length; i++) {
            (function(idx) {
                var tag = new models.Tag({
                    author: u._id,
                    article: article._id,
                    name: tags[idx],
                    created: moment().utc().format()
                });
                tag.save(function(err, tag) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                });
            }(i));
        }
    });
};

exports.remove = function(req, res, next) {
    var articleId = req.body.id;

    models.Article.remove({
        _id: articleId
    }, function(err, art) {
        if (err || !art) {
            next;
            return;
        } else {
            res.json(CONSTS.HTTPOK, {
                status: 0,
                msg: art
            });
        }
    });
};

exports.edit = function(req, res, next) {
    var u = req.u;
    var articleId = req.body.id;
    var title = req.body.title;
    var html = req.body.html;
    var markdown = req.body.markdown;
    var tags = JSON.parse(req.body.tags);

    if (Common.isTrimmedEmpty(title)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "title is empty"
        });
        return;
    }

    if (Common.isTrimmedEmpty(html)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "html is empty"
        });
        return;
    }

    if (Common.isTrimmedEmpty(markdown)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "markdown is empty"
        });
        return;
    }

    if (!(tags instanceof Array)) {
        res.json(CONSTS.HTTPOK, {
            status: 1,
            error: "tags should be array"
        });
        return;
    }

    models.Article.findOne({
        _id: articleId
    }, function(err, article) {
        if (err || !article) {
            next();
            return;
        } else {
            article.title = title;
            article.html = html;
            article.markdown = markdown;
            article.tags = tags;

            article.save(function(err, article) {
                if (err) {
                    res.json(CONSTS.HTTPOK, {
                        status: 1,
                        error: "db error"
                    });
                    return;
                }

                models.Tag.remove({
                    article: articleId
                }, function(err, tags) {
                    if (err) {
                        next();
                        return;
                    } else {
                        for (var i = 0; i < tags.length; i++) {
                            (function(idx) {
                                var tag = new models.Tag({
                                    author: u._id,
                                    article: article._id,
                                    name: tags[idx],
                                    created: moment().utc().format()
                                });
                                tag.save(function(err, tag) {
                                    if (err) {
                                        console.log(err);
                                        return;
                                    }
                                });
                            }(i));
                        }
                    }
                });


                res.json(CONSTS.HTTPOK, {
                    status: 0,
                    msg: article
                });

            });
        }

    });
};

exports.publishList = function(req, res, next) {
    var u = req.u;
    var body = req.body;
    var ps = body.ps;
    var opts = {};

    (!ps || ps < 0) && (ps = 10);

    if (Common.isDefined(body.afterTime)) {
        opts.created = {
            "$gt": new Date(body.afterTime),
        };
    } else if (Common.isDefined(body.beforeTime)) {
        opts.created = {
            "$lt": new Date(body.beforeTime),
        };
    }

    models.Article.find(opts)
        .populate('author')
        .sort({
            created: -1
        })
        .limit(ps)
        .exec(function(err, articles) {
            if (err) {
                res.json(CONSTS.HTTPOK, {
                    status: 1,
                    error: 'db error'
                });
                return;
            }

            if (!articles) {
                res.json(CONSTS.HTTPOK, {
                    status: 0,
                    msg: []
                });
                return;
            }

            res.json(CONSTS.HTTPOK, {
                status: 0,
                msg: articles
            });
        });
};
exports.authorArtlist = function(req, res, next) {
    var u = req.u;
    var aid = req.body.aid;
    var pn = req.body.pn;
    var ps = req.body.ps;

    (!pn || pn < 0) && (pn = 0);
    (!ps || ps < 0) && (ps = 10);

    models.Article.find({
            author: aid
        })
        .populate('author')
        .sort({
            created: -1
        })
        .skip(pn * ps)
        .limit(ps)
        .exec(function(err, articles) {
            if (err) {
                res.json(CONSTS.HTTPOK, {
                    status: 1,
                    error: 'db error'
                });
                return;
            }

            if (!articles) {
                res.json(CONSTS.HTTPOK, {
                    status: 0,
                    msg: []
                });
                return;
            }

            res.json(CONSTS.HTTPOK, {
                status: 0,
                msg: articles
            });
        });
}
exports.publishSearch = function(req, res, next) {};

exports.publishHot = function(req, res, next) {

};
exports.findbyid = function(req, res, next) {
    var articleId = req.body.id;

    models.Article.findOne({
            _id: articleId
        })
        .populate('author')
        .exec(function(err, article) {
            if (err || !article) {
                next();
                return;
            }

            res.json(CONSTS.HTTPOK, {
                status: 0,
                msg: article
            });
        });
}
exports.listByDate = function(req, res, next) {
    var u = req.u;
    var body = req.body;
    var opts = {};
    var created = {
        created: 1
    };

    if (Common.isDefined(body.afterTime)) {
        opts.created = {
            "$gt": new Date(body.afterTime)
        };
        opts._id = {
            "$ne": body.id
        };
        created = {
            created: 1
        };
    } else if (Common.isDefined(body.beforeTime)) {
        opts.created = {
            "$lt": new Date(body.beforeTime)
        };
        opts._id = {
            "$ne": body.id
        };
        created = {
            created: -1
        };
    }

    models.Article.findOne(opts)
        .sort(created)
        .exec(function(err, article) {
            if (err || !article) {
                res.json(CONSTS.HTTPOK, {
                    status: 1,
                    error: 'db error'
                });
                return;
            }

            res.json(CONSTS.HTTPOK, {
                status: 0,
                msg: article
            });
        });
};